﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ServiceStack;
using ZH.Infrastructure.Attr;
using ZH.Infrastructure.Dto.Request.Login;
using ZH.Infrastructure.Dto.Response;
using ZH.Infrastructure.Dto.Response.admin;
using ZH.Infrastructure.EFCore.MySql;
using ZH.Infrastructure.IOC;
using ZH.Infrastructure.Redis;
using ZH.Infrastructure.Tools;
using ZH.Service.Interface;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace ZH.Service.Instance
{

    [Inject_]
    public class Login_Service : Base_Service, I_Login_Service
    {
        private readonly Login_IOC _login_IOC;
        private readonly Mobile_IOC _mobile_IOC;
        private readonly IConfiguration _configuration;
        private readonly RedisStringService _redisStringService;
        public Login_Service(RedisStringService redisStringService, IConfiguration configuration, Login_IOC login_IOC, Mobile_IOC mobile_IOC)
        {
            _login_IOC = login_IOC;
            _configuration = configuration;
            _redisStringService = redisStringService;
            _mobile_IOC = mobile_IOC;

        }

        /// <summary>
        /// 验证用户登录是否有效
        /// </summary>
        /// <param name="code"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public User_Response_Dto? Check_Login(string code, string account)
        {
            var _user = _redisStringService.Get<string>(code);
            if (!string.IsNullOrEmpty(_user))
            {
                return JsonConvert.DeserializeObject<User_Response_Dto>(_user);
            }


            var key = _configuration["Redis:Keys:Check_Login"];
            //如果在此处你查询了这个
            var jwt = _redisStringService.Get<string>(key + account);
            if (code == jwt)
            {
                var user = _login_IOC._admin_EFcore.QueryAll(d => d.Uaccount == account).Select(d => new
                User_Response_Dto
                {
                    id = d.Uid,
                    name = d.Uname,
                    account = d.Uaccount,
                    isActive = d.UisActive,
                    isBan = d.UisBan,
                    time = d.UcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).Single();
                _redisStringService.Set(code, JsonConvert.SerializeObject(user), DateTime.Now.AddSeconds(60));
                return user;
            }
            else
                return null;

        }



        public async Task<Api_Response_Dto> Init_Users()
        {
            var users = await _login_IOC._admin_EFcore.QueryAll().ToListAsync();
            users.ForEach(d =>
            {
                var s = Config.GUID2();
                d.Usalt = s;
                d.Upassword = EncryptUtil.LoginMd5("123456", s);
            });
            _login_IOC._admin_EFcore.UpdateRange(users);
            _login_IOC._admin_EFcore.SaveChanges();

            return Result(1);
        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Logins(Login_Request_Dto dto)
        {
            var iq = _login_IOC._admin_EFcore.QueryAll(d => d.Uaccount == dto.account);
            if (!await iq.AnyAsync())
            {
                return new Api_Response_Dto()
                {
                    code = Api_Code.fail,
                    message = "账号或者密码错误"
                };
            }
            var user = await iq.SingleAsync();
            //判断密码是否正确
            var pwd = EncryptUtil.LoginMd5(dto.password!, user.Usalt!);
            if (user.Upassword != pwd)
            {
                return Result(0, "账号或者密码错误");
            }
            if (user.UisBan == 1)
            {
                return Result(0, "账号已禁用");
            }

            AddLog(new Adminloginlog
            {
                LlId = Config.GUID(),
                LlCreateTime = DateTime.Now,
                LlUid = user.Uid,
                LlCode = dto.code,//这个是本次登录的凭据
                LlResult = 0
            });



            var key = _configuration["Redis:Keys:Check_Login"];
            _redisStringService.Set<string>(key + user.Uaccount, dto.code!, DateTime.Now.AddSeconds(60 * 60 * 24));//一天有效


            return Result(1, "ok");
        }

        private int AddLog(Adminloginlog log)
        {
            _login_IOC._adminloginlog_EFCore.Add(log);

            return _login_IOC._adminloginlog_EFCore.SaveChanges();
        }

        public async Task<Api_Response_Dto> HQTJ()
        {
            
                var dd = await _mobile_IOC._order_EFCore.QueryAll().ToListAsync();
                var zyh = _mobile_IOC._mobile_EFCore.QueryAll().ToList().Count();
                var zsc = dd.Sum(d => d.OrMoney);
                var zdds = dd.Count();
                int year = dd.FirstOrDefault()?.OrCreatTime.Value.Year ?? DateTime.Now.Year;
                var allMonths = Enumerable.Range(1, 12).ToList();
                var monthlySum = allMonths.Select(month => new
                {
                  
                    Month = month,
                    TotalMoney = dd
                                    .Where(order => order.OrCreatTime.Value.Year == year &&
                                                   order.OrCreatTime.Value.Month == month)
                                    .Sum(order => order.OrMoney)
                }).ToList();
            

            return Result(1,"ok",new { 
            zyh,
            zsc,
            zdds,
            monthlySum
            
            });
        
        }
    }
}
